//
//  WKYouTableViewCell.m
//  Walk
//
//  Created by cesh on 16/9/6.
//  Copyright © 2016年 cesh. All rights reserved.
//

#import "WKYouTableViewCell.h"
#import "WKSingleViewController.h"
#import "WKAudioTool.h"
#import <UIImageView+WebCache.h>


@interface WKYouTableViewCell()

@property (weak, nonatomic) IBOutlet UIImageView *iconImg;
@property (weak, nonatomic) IBOutlet UILabel *nameLbl;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (weak, nonatomic) IBOutlet UIImageView *messageImg;
@property (weak, nonatomic) IBOutlet UIImageView *animationImage;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *messageImgWidthConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *messageImgHeightConstraint;

@property (strong, nonatomic) UIImageView *imgV;

@property (strong, nonatomic) NSMutableArray *usersNameHead;

@end

@implementation WKYouTableViewCell

- (NSMutableArray *)usersNameHead {
    if (_usersNameHead == nil) {
        _usersNameHead = [NSMutableArray array];
    }
    return _usersNameHead;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.iconImg.userInteractionEnabled = YES;
    [self.iconImg addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(presentSingleVC)]];
    
    self.iconImg.layer.cornerRadius = 25;
    self.iconImg.layer.masksToBounds = YES;
}

//点击头像弹出单人VC
- (void)presentSingleVC {
    if ([self.delegate respondsToSelector:@selector(youTableViewCell:popSingleVC:)]) {
        [self.delegate youTableViewCell:self popSingleVC:[[WKSingleViewController alloc]init]];
    }
}

- (void)setMessageType:(MessageType)messageType {
    switch (messageType) {
        case MessageTypeText:
            break;
        case MessageTypeAudio:
        {
            
            UILabel *durationLabel = [[UILabel alloc]init];
            durationLabel.font = [UIFont systemFontOfSize:12.0];
            durationLabel.textColor = [UIColor colorWithRed:0x9b / 255.0 green:0x9b / 255.0 blue:0x9b / 255.0 alpha:1.0];
            durationLabel.text = [NSString stringWithFormat:@"%li\"", (long)self.audioSeconds];
            [durationLabel sizeToFit];
            durationLabel.right = self.messageLabel.width + 30;
            durationLabel.bottom = self.messageLabel.height;
            [self.messageLabel addSubview:durationLabel];
            
            //给对话框添加点击播放语音功能
            self.messageImg.userInteractionEnabled = YES;
            UITapGestureRecognizer *playAudio = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playAudio)];
            [self.messageImg addGestureRecognizer:playAudio];
        }
            break;
        case MessageTypeVideo:
            break;
        case MessageTypePicture:
        {
            self.messageLabel.hidden = YES;
            self.messageImg.userInteractionEnabled = YES;
            [self showImage];
        }
            break;
        case MessageTypeLocation:
            break;
        default:
            break;
    }
}

- (void)playAudio {
    if([self.message.body isKindOfClass:[EMVoiceMessageBody class]]){
        [WKAudioTool playWithMessage:self.message animation:self.animationImage isMe:NO];
    }
}

//根据消息from的不同，本地化存储相应的头像和昵称
- (void)setMessage:(EMMessage *)message {
    
    _message = message;
    //文字消息
    if ([message.body isKindOfClass:[EMTextMessageBody class]]) {
        self.animationImage.hidden = YES;
        EMTextMessageBody *body = (EMTextMessageBody *)message.body;
        self.messageLabel.text = body.text;
    }
    // 语音消息
    else if ([message.body isKindOfClass:[EMVoiceMessageBody class]]) {
        self.animationImage.hidden = NO;
        self.messageLabel.text = @"            ";
    }
    //图片消息
    else if ([message.body isKindOfClass:[EMImageMessageBody class]]) {
        self.animationImage.hidden = YES;
        self.messageLabel.text = @"                             .\n\n\n\n\n\n";
    }
    
    [self layoutIfNeeded];
    self.messageImgWidthConstraint.constant = self.messageLabel.width + 25;
    self.messageImgHeightConstraint.constant = self.messageLabel.height + 20;
    
    //通过环信id获取用户id
    NSString *hx_user_id = message.from;
    NSString *app_user_id = [hx_user_id substringFromIndex:2];
    self.userID = app_user_id;
    
    // 如果本地没有存储对方的昵称和头像,从网络获取并存储到本地
    self.usersNameHead = [NSMutableArray arrayWithContentsOfFile:otherUsersNameHead];
    for (NSDictionary *dict in self.usersNameHead) {
        NSString *from = dict[@"from"];
        if ([from isEqualToString:message.from]) {
            self.nameLbl.text = dict[@"name"];
            NSData *imgData = dict[@"head"];
            self.iconImg.image = [UIImage imageWithData:imgData];
            return;
        }
    }
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    //接收类型不一致请替换一致text/html或别的
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     @"text/plain",
                                                     nil];
    NSDictionary * dict = @{
                            @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                            @"userID" :  app_user_id
                            };
    [mgr GET:[NSString stringWithFormat:@"%@Frog/getUserInfo", URL] parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *name = responseObject[@"data"][@"nickname"];
        self.nameLbl.text = name;
        NSString *head = responseObject[@"data"][@"headerImg"][@"thumb_url"];
        self.iconImg.image = [UIImage imageNamed:@"default_head"];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            UIImage *headImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:head]]];
            
            self.usersNameHead = [NSMutableArray arrayWithContentsOfFile:otherUsersNameHead];
            NSDictionary *userNameHead = @{
                                           @"from" : message.from,
                                           @"name" : name,
                                           @"head" : UIImagePNGRepresentation(headImg)
                                           };
            [self.usersNameHead addObject:userNameHead];
            
            NSLog(@"用户昵称和头像写入成功：%i ", [self.usersNameHead writeToFile:otherUsersNameHead atomically:YES]);
            
            dispatch_sync(dispatch_get_main_queue(), ^{
                if (head != nil) {
                    self.iconImg.image = headImg;
                }
            });
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"个人详情失败 %@", error);
    }];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

}

- (CGFloat)cellHeight {
    CGFloat height = 0;
    
    //顶部
    height += 36;
    [self layoutIfNeeded];
    height += self.messageLabel.bounds.size.height;
    
    height += 18;
    
    return height;
}

-(void)showImage{
    UIImageView *imgV = [[UIImageView alloc]init];
    imgV.origin = CGPointMake(11, 5);
    imgV.size = CGSizeMake(110, 110);
    // 获取图片的消息体
    EMImageMessageBody *imgBody = (EMImageMessageBody *)self.message.body;
    // 判断本地图片是否存在
    BOOL isImgExit = [[NSFileManager defaultManager] fileExistsAtPath:imgBody.thumbnailLocalPath];
    if (isImgExit) {
        imgV.image = [UIImage imageWithContentsOfFile:imgBody.thumbnailLocalPath];
    }else{
        //从网络加载图片
        [imgV sd_setImageWithURL:[NSURL URLWithString:imgBody.thumbnailRemotePath] placeholderImage:[UIImage imageNamed:@"default_head"]];
    }
    [self.messageImg addSubview:imgV];
    self.imgV = imgV;
    //添加点击图片事件
    imgV.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapOnImg = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(popBigImgView)];
    [imgV addGestureRecognizer:tapOnImg];
}

- (void)popBigImgView {
    UIImageView *bigImgV = [[UIImageView alloc]init];
    bigImgV.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
    bigImgV.frame = [UIScreen mainScreen].bounds;
    bigImgV.image = self.imgV.image;
    bigImgV.contentMode = UIViewContentModeScaleAspectFit;
    [[UIApplication sharedApplication].keyWindow addSubview:bigImgV];
    
    //给bigImgV添加点击推出的方法
    bigImgV.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapOnBigImg = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignBigImg:)];
    [bigImgV addGestureRecognizer:tapOnBigImg];
}

- (void)resignBigImg:(UITapGestureRecognizer *)tap {
    [tap.view removeFromSuperview];
}
@end
